//
//  CZStatusPictureView.swift
//  微博08
//
//  Created by apple on 16/3/3.
//  Copyright © 2016年 itcast. All rights reserved.
//

import UIKit
import SDWebImage

// 最大列数
private let maxColumn = 3

// cell之间的间距
private let CZStatusPictureViewCellMargin: CGFloat = 10

// 计算一个cell宽高
private let CZStatusPictureViewWH = (UIScreen.width - 2 * CZStatusCellMargin - (CGFloat(maxColumn) - 1) * CZStatusPictureViewCellMargin) / CGFloat(maxColumn)

// cellSize
private let CZStatusPictureViewCellSize = CGSize(width: CZStatusPictureViewWH, height: CZStatusPictureViewWH)

private let ReuseIdentifier = "ReuseIdentifier"

// 在class外面是全局的只有一个
//let layout = UICollectionViewFlowLayout()
class CZStatusPictureView: UICollectionView {
    
    // MARK: - 属性
    
    // 布局,注意: 一个collectionView需要有一个单独的布局.布局不能给其它的collectionView使用的
    let layout = UICollectionViewFlowLayout()
    
    // 微博数据
    var status: CZStatus? {
        didSet {
            // 计算微博配图的大小
            let viewSzie = calcViewSize()
            
            // 重新约束
            self.snp_updateConstraints { (make) -> Void in
                make.size.equalTo(viewSzie)
            }
            
            // 刷新collectionView
            self.reloadData()
        }
    }
    
    /**
     计算微博配图的大小
     
     - returns: 大小
     */
    private func calcViewSize() -> CGSize {
        let count = status?.storePictureURLs?.count ?? 0
        
        // 没有图片
        if count == 0 {
            return CGSizeZero
        }
        
        // 1.张图片
        if count == 1 {
            var size = CGSize(width: 180, height: 120)
            // 获取图片的url
            let iamgeURLString = status?.storePictureURLs?.first?.absoluteString
            
            // 获取图片,有可能失败
            if let image = SDImageCache.sharedImageCache().imageFromDiskCacheForKey(iamgeURLString!) {
                
                // 获取图片的大小显示
                size = image.size
            }
            
            // 判断图片太小或太大
            if size.width < 40 {
                size.width = 40
            } else if size.width > UIScreen.width * 0.5 {
                size.width = UIScreen.width * 0.5
            }
            
            // cell和collectionView一样大
            layout.itemSize = size
            layout.minimumInteritemSpacing = 0
            layout.minimumLineSpacing = 0
            return size
        }
        
        // 设置layout
        layout.itemSize = CZStatusPictureViewCellSize
        layout.minimumLineSpacing = CZStatusPictureViewCellMargin
        layout.minimumInteritemSpacing = CZStatusPictureViewCellMargin

        // 其它情况
        // 计算列数
        // 判断是否是4张,4张显示2列,其它情况判断个数是否大于最大列数,小于最大列数显示count列, 大于最大列数显示最大列数
//        let column = count == 4 ? 2: count < maxColumn ? count : maxColumn
        
        // 假设3列
        var column = maxColumn
        if count == 2 || count == 4 {
            column = 2
        }
        
        // (count + maxColumn - 1) / maxColumn,算页数,前提 maxColumn必须是Int类型
        // count = 5, 8 + 3 - 1 / 3
//        let row =  count == 4 ? 2 : (count + maxColumn - 1) / maxColumn
        let row = (count + column - 1) / column
        
        // 计算宽度
        let width = CGFloat(column) * CZStatusPictureViewWH + (CGFloat(column) - 1) * CZStatusPictureViewCellMargin
        
        // 计算高度
        let height = CGFloat(row) * CZStatusPictureViewWH + (CGFloat(row) - 1) * CZStatusPictureViewCellMargin
        
//        print("count: \(count), column: \(column), row: \(row), width: \(width), height: \(height)")
        
        return CGSize(width: width, height: height)
    }

    init() {
        super.init(frame: CGRectZero, collectionViewLayout: layout)
        
        backgroundColor = UIColor.clearColor()
        
        // 设置数据源和代理
        self.delegate = self
        self.dataSource = self
        
        // 注册cell
        self.registerClass(CZStatusPictureViewCell.self, forCellWithReuseIdentifier: ReuseIdentifier)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

}

extension CZStatusPictureView: UICollectionViewDataSource, UICollectionViewDelegate {
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return status?.storePictureURLs?.count ?? 0
    }
    
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(ReuseIdentifier, forIndexPath: indexPath) as! CZStatusPictureViewCell
        
//        cell.backgroundColor = indexPath.item % 2 == 0 ? UIColor.redColor() : UIColor.brownColor()
        // 如果失败说明服务器返回的数据有问题
//        let urlString = status?.pic_urls?[indexPath.item]["thumbnail_pic"] as! String
        let url = status?.storePictureURLs?[indexPath.item]
        
        cell.imageURL = url
        
        return cell
    }
}

// MARK: - 配图cell
class CZStatusPictureViewCell: UICollectionViewCell {
    
    // MARK: - 属性
    var imageURL: NSURL? {
        didSet {
            // sd来显示图片
            bkgImageView.sd_setImageWithURL(imageURL)
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        prepareUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func prepareUI() {
        // 添加控件
        contentView.addSubview(bkgImageView)
        
        // 添加约束
        bkgImageView.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(contentView)
        }
        
        // 设置填充模式
        bkgImageView.contentMode = UIViewContentMode.ScaleAspectFill
        // 裁剪
        bkgImageView.clipsToBounds = true
    }
    
    // MARK: - 懒加载
    // 背景图片
    private lazy var bkgImageView: UIImageView = UIImageView(image: nil)
}
